<template>
  <div class="consultant_dailog">
    <el-dialog
      title="选择会诊方"
      :visible.sync="consDlgShow"
      :destroy-on-close="true"
      width="80%"
      top="5vh"
      :fullscreen="false"
      @open="dialogOpen"
    >
      <div slot="title" class="header-title">
        <div class="goback" @click="goback" v-if="dlgTitle.length>1">
          <i class="el-icon-arrow-left"></i>
        </div>
        <el-breadcrumb class="breadcrumb" separator="/">
          <el-breadcrumb-item v-for="item in dlgTitle" :key="item.title">{{item.title}}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="cons_container">
        <!-- <div class="cons_doctor_box" v-if="dialogType == 0">
          <div class="cons_doctor_form"> -->
        <!-- <el-form
              :inline="true"
              :model="consultantDoctorForm"
              class="demo-form-inline select-doctor-form"
            >
              <el-form-item label="医院">
                <el-select
                  size="small"
                  v-model="consultantDoctorForm.Hospital"
                  filterable
                  default-first-option
                  clearable
                  placeholder="请选择医院"
                  @change="HospChange"
                >
                  <el-option
                    v-for="item in HospitalOptions"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="科室">
                <el-select
                  size="small"
                  v-model="consultantDoctorForm.Department"
                  filterable
                  allow-create
                  default-first-option
                  clearable
                  placeholder="请选择科室"
                  @change="HospDepDocChange"
                >
                  <el-option
                    v-for="item in DepartmentOptions"
                    :key="item.id"
                    :label="item.departmentName"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="医生" class="form_item_doctor">
                <el-input
                  size="small"
                  v-model="consultantDoctorForm.Doctor"
                  placeholder="请输入医生"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item label="团队">
                <el-select
                  size="small"
                  v-model="consultantDoctorForm.Team"
                  filterable
                  allow-create
                  default-first-option
                  clearable
                  placeholder="请选择团队"
                  @change="TeamChange"
                >
                  <el-option
                    v-for="item in TeamOptions"
                    :key="item.id"
                    :label="item.teamName"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </div> -->
        <!-- <div class="loading_box" v-loading="loading">
            <doctorWrap
              :doctorData="doctorData"
              :applyTheme="applyTheme"
              @doctorDetails="goDoctorDetails"
              @selectedDoctor="selectedDoctor"
              @zzIdSelected="zzIdSelected"
            />
          </div>
        </div> -->
        <div class="cons_box" v-if="dialogType == 2">
          <div class="cons_doctor_info_wrap">
            <doctorDetails
              :doctor-details-info="doctorDetailsInfo"
              :select-disabled="doctorSelectDisabled"
              @selectedDoctor="selectedDoctor"
            />
          </div>
        </div>
        <div class="cons_teamHospital_box" v-if="dialogType == 1">
          <div class="cons_teamHospital_form">
            <el-form :inline="true" class="demo-form-inline">
              <el-form-item label="搜索">
                <el-input size="small" v-model="teamOrHospitalName" placeholder></el-input>
              </el-form-item>
            </el-form>
          </div>
          <div class="cons_teamHospital_wrap loading_box" v-loading="loading">
            <teamHospitalWrap
              @teamDetails="goTeamDetails"
              @hospitalDetails="goHospitalDetails"
              @selectTeamHospital="selectTeamHospitalDep"
              :team-hospital-list="teamHospitalList"
              :cons-type="teamOrHospital"
            />
          </div>
        </div>
        <!-- <div class="cons_box" v-if="dialogType == 3">
          <div class="cons_team_details_wrap">
            <teamDetails
              :teamDetails="teamDetailsInfo"
              :teamDetailsDoctorList="teamDetailsDoctorList"
              @selectTeam="selectTeamHospitalDep"
              @doctorDetails="goTeamDoctorDetails"
            />
          </div>
        </div> -->
        <div class="cons_box" v-if="dialogType == 4">
          <div class="cons_team_details_wrap">
            <hospitalDetails
              :hospital-details="hospitalDetailsInfo"
              :department-options="DepartmentOptions"
              @selectHospitalDep="selectTeamHospitalDep"
            />
          </div>
        </div>
      </div>
      <div class="cons_footer" v-if="dialogType == 0">
        <el-button
          v-if="applyTheme == '3'"
          class="nav_save"
          @click="selectedDoctorMDT"
          type="primary"
        >确定</el-button>
        <div class="page_wrap">
          <paginationCont
            :total="totalCount"
            :page.sync="currentPage"
            :limit.sync="pageSize"
            @pagination="fetchData"
          />
        </div>
      </div>
      <div class="cons_footer" v-if="dialogType == 1">
        <div class="page_wrap">
          <paginationCont
            :total="totalCountTH"
            :page.sync="currentPageTH"
            :limit.sync="pageSizeTH"
            @pagination="searchTeamHospital"
          />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import {
  getSysHospitalGetPages,
  getSysHospitalGetList,
  getSysDepartmentGetList,
  getRemoteTeamGetPages,
  getRemoteTeamGetList,
  getSysUserGetPagesByExpert,
  getRemoteTeamUserGetPages,
  postRemoteExpertDiagnosisAddRemoteExperts,
  deleteRemoteExpertDiagnosis
} from '@/api/api.js'
import paginationCont from '@/components/Pagination/index'
import doctorDetails from '@/components/consultant/doctorDetails'
// import doctorWrap from '@/components/consultant/doctorWrap'
import teamHospitalWrap from '@/components/consultant/teamHospitalWrap'
// import teamDetails from '@/components/consultant/teamDetails'
import hospitalDetails from '@/components/consultant/hospitalDetails'
import bus from '@/api/bus'
export default {
  props: {
    // 0: 选择医生, 1: 团队、医院
    consType: {
      type: Number,
      default: 0
    },
    consultantDlgShow: {
      type: Boolean,
      default: false
    },
    // 申请单id
    consultationId: {
      type: String
    },
    // 申请主题
    applyTheme: {
      type: String
    },
    // 选择的团队医院科室
    consultantTeam: {
      type: Object
    }
  },
  components: {
    paginationCont,
    doctorDetails,
    // doctorWrap,
    teamHospitalWrap,
    // teamDetails,
    hospitalDetails
  },
  data() {
    return {
      loading: false,
      UserId: '', // 用户id
      // 0：选择医生, 2：医生详情, 1：团队、医院 3：团队详情, 4：医院详情
      dialogType: 0,
      totalCount: 0,
      pageSize: 10,
      currentPage: 1,
      dlgTitle: [
        { title: '选择会诊医生', path: 0 }
      ],
      saveShow: false, // 如果多选，显示确定提交按钮
      consultantDoctorForm: {
        Hospital: '',
        Department: '',
        Doctor: '',
        Team: ''
      },
      HospitalOptions: [],
      DepartmentOptions: [],
      TeamOptions: [],
      doctorData: [], // 医生列表数据
      doctorSelectDisabled: false, // 医生详情选择医生按钮是否显示
      doctorDetailsInfo: null, // 医生信息
      totalCountTH: 0, // 团队或医院分页
      pageSizeTH: 10,
      currentPageTH: 1,
      teamHospitalList: [],
      teamOrHospital: 'hospital',
      teamOrHospitalName: '',
      teamDetailsInfo: null, // 团队信息
      teamDetailsDoctorList: null, // 团队成员列表
      hospitalDetailsInfo: null, // 医院信息
      zzId: '', // 多选时的主责id
      consultantDoctorData: [] // 已选择的会诊医生列表
    }
  },
  created() {
    this.UserId = this.$store.state.user.id
    bus.$on('consultantDoctorChange', (data) => {
      this.consultantDoctorData = data // 接收
    })
  },
  beforeDestroy() {
    bus.$off('consultantDoctorChange')
  },
  computed: {
    consDlgShow: {
      get() {
        return this.consultantDlgShow
      },
      set(val) {
        this.$emit('update:consultantDlgShow', val)
      }
    }
  },
  methods: {
    dialogOpen() {
      this.dialogType = this.consType == 0 ? 0 : 1
      this.dlgTitle = []
      // this.getDepartmentOptions();
      if (this.dialogType == 0) {
        this.dlgTitle = [{ title: '选择会诊医生', path: 0 }]
        this.getHospitalOptions()
        this.getTeamOptions()
        this.searchDoctor()
      } else if (this.dialogType == 1) {
        this.teamOrHospital = 'hospital'
        this.teamOrHospitalName = ''
        this.getHospitalList()
        this.dlgTitle = [{ title: '接收医院', path: 0 }]
      }
    },
    // 获取医院列表
    getHospitalOptions() {
      const params = {
        name: '',
        IsRemote: '1'
      }
      getSysHospitalGetList(params).then((res) => {
        if (res && res.code == 10000) {
          this.HospitalOptions = res.content.list
        }
      })
    },
    // 获取科室列表
    getDepartmentOptions() {
      const params = {
        HospitalCode: this.consultantDoctorForm.Hospital,
        DepartmentName: ''
      }
      getSysDepartmentGetList(params).then((res) => {
        if (res && res.code == 10000) {
          this.DepartmentOptions = res.content.list
        }
      })
    },
    // 获取团队列表
    getTeamOptions() {
      const params = {}
      getRemoteTeamGetList(params).then((res) => {
        if (res && res.code == 10000) {
          this.TeamOptions = res.content.list
        }
      })
    },
    // 医院选择\科室选择\医生输入
    HospDepDocChange() {
      this.currentPage = 1
      this.consultantDoctorForm.Team = ''
      this.searchDoctor()
    },
    // 医院选择
    HospChange() {
      this.currentPage = 1
      this.consultantDoctorForm.Team = ''
      this.consultantDoctorForm.Department = ''
      if (!this.consultantDoctorForm.Hospital) {
        this.DepartmentOptions = []
      } else {
        this.getDepartmentOptions()
      }
      this.searchDoctor()
    },
    // 团队选择
    TeamChange() {
      this.currentPage = 1
      this.consultantDoctorForm.Hospital = ''
      this.consultantDoctorForm.Department = ''
      this.consultantDoctorForm.Doctor = ''
      this.searchDoctor()
    },
    // 医生搜索
    searchDoctor() {
      const that = this
      that.loading = true
      // 判断是否为团队搜索医生
      if (!that.consultantDoctorForm.Team) {
        const params = {
          pageSize: that.pageSize, // 页面大小
          pageNumber: that.currentPage, // 页码
          ApplyId: that.consultationId,
          sortOrder: 'Desc',
          UserId: that.UserId,
          HospitalCode: that.consultantDoctorForm.Hospital,
          DeptCode: that.consultantDoctorForm.Department,
          UserName: that.consultantDoctorForm.Doctor,
          IsRemote: '1'
        }
        getSysUserGetPagesByExpert(params).then((res) => {
          if (res && res.code == 10000) {
            that.doctorData = res.content.list
            that.totalCount = res.content.totalCount
            that.pageSize = res.content.pageSize
            that.loading = false
          }
        }).catch(() => {
          that.loading = false
        })
      } else {
        const params = {
          pageSize: that.pageSize, // 页面大小
          pageNumber: that.currentPage, // 页码
          ApplyId: that.consultationId,
          sortOrder: 'Desc',
          TeamId: that.consultantDoctorForm.Team
        }
        getRemoteTeamUserGetPages(params).then((res) => {
          if (res && res.code == 10000) {
            this.doctorData = res.content.list
            this.totalCount = res.content.totalCount
            this.pageSize = res.content.pageSize
            that.loading = false
          }
        }).catch(() => {
          that.loading = false
        })
      }
    },
    // 医生详情
    goDoctorDetails(data) {
      this.doctorSelectDisabled = data.btnShow
      this.doctorDetailsInfo = this.doctorData[data.index]
      this.dialogType = 2
      const _title = this.doctorDetailsInfo.userName
      this.dlgTitle = this.dlgTitle.concat([{ title: _title, path: 0 }])
    },
    // 后退
    goback() {
      const _len = this.dlgTitle.length
      this.dialogType = this.dlgTitle[_len - 1].path
      this.dlgTitle.pop()
      if (this.dialogType == 0) {
        this.searchDoctor()
      } else if (this.dialogType == 3) {
        this.getTeamDoctorList(this.teamDetailsInfo.id)
      }
    },
    // 获取医院列表\分页
    getHospitalList() {
      const that = this
      that.loading = true
      const params = {
        name: that.teamOrHospitalName,
        pageSize: that.pageSizeTH, // 页面大小
        pageNumber: that.currentPageTH, // 页码
        sortOrder: 'Desc'
      }
      getSysHospitalGetPages(params).then((res) => {
        if (res && res.code == 10000) {
          that.teamHospitalList = res.content.list
          that.totalCountTH = res.content.totalCount
          that.pageSizeTH = res.content.pageSize
          that.loading = false
        }
      }).catch(() => {
        that.loading = false
      })
    },
    // 获取团队列表\分页
    getTeamList() {
      const that = this
      that.loading = true
      const params = {
        TeamName: that.teamOrHospitalName,
        pageSize: that.pageSizeTH, // 页面大小
        pageNumber: that.currentPageTH, // 页码
        sortOrder: 'Desc'
      }
      getRemoteTeamGetPages(params).then((res) => {
        if (res && res.code == 10000) {
          that.teamHospitalList = res.content.list
          that.totalCountTH = res.content.totalCount
          that.pageSizeTH = res.content.pageSize
          that.loading = false
        }
      }).catch(() => {
        that.loading = false
      })
    },
    // 获取团队成员列表
    getTeamDoctorList(teamid) {
      const that = this
      that.loading = true
      const params = {
        pageSize: that.pageSize, // 页面大小
        pageNumber: that.currentPage, // 页码
        ApplyId: '', // that.consultationId,
        TeamId: teamid,
        sortOrder: 'Desc'
      }
      getRemoteTeamUserGetPages(params).then((res) => {
        if (res && res.code == 10000) {
          this.teamDetailsDoctorList = res.content.list
          that.loading = false
        }
      }).catch(() => {
        that.loading = false
      })
    },
    // 搜索医院、团队
    searchTeamHospital() {
      if (this.teamOrHospital == 'hospital') {
        this.getHospitalList()
      } else {
        this.getTeamList()
      }
    },
    teamHospitalChange() {
      this.currentPageTH = 1
      if (this.teamOrHospital == 'hospital') {
        this.getHospitalList()
      } else {
        this.getTeamList()
      }
    },
    // 团队详情
    async goTeamDetails(data) {
      this.teamDetailsInfo = this.teamHospitalList[data.index]
      await this.getTeamDoctorList(this.teamDetailsInfo.id)
      this.dialogType = 3
      const _title = this.teamDetailsInfo.teamName
      this.dlgTitle = this.dlgTitle.concat([{ title: _title, path: 1 }])
    },
    // 医院详情
    goHospitalDetails(data) {
      this.hospitalDetailsInfo = this.teamHospitalList[data.index]
      this.dialogType = 4
      const _title = this.hospitalDetailsInfo.name
      this.dlgTitle = this.dlgTitle.concat([{ title: _title, path: 1 }])
    },
    // 团队详情选择团队
    childSelectTeam(data) {
      // console.log('子组件选择团队')
    },
    // 团队到医生详情
    goTeamDoctorDetails(data) {
      this.doctorDetailsInfo = this.teamDetailsDoctorList[data.index]
      this.dialogType = 2
      this.doctorSelectDisabled = true
      const _titArr = [{ title: this.doctorDetailsInfo.userName, path: 3 }]
      this.dlgTitle = this.dlgTitle.concat(_titArr)
    },
    // 医院详情选择医院\科室\团队
    selectTeamHospitalDep(data) {
      this.$emit('refreshConsultantTeam', data)
      // const consTeam = this.getTeamHospitalDepData(data)
      // const that = this;
      // if (data) {
      //   let _txt = '';
      //   if (that.consultantDoctorData.length > 0) {
      //     _txt = '删除已选会诊方，并'
      //   }

      //   const _strTeam = consTeam.TeamName ? consTeam.TeamName : ''
      //   const _strHosp = consTeam.HospitalName ? consTeam.HospitalName : ''
      //   const _strDep = consTeam.DepName ? '-' + consTeam.DepName : ''
      //   that.$confirm('确认' + _txt + '选择 ' + _strTeam + _strHosp + _strDep + " 会诊？", '提示', {
      //     confirmButtonText: '确定',
      //     cancelButtonText: '取消',
      //     type: 'warning'
      //   }).then(async () => {
      this.consDlgShow = false
      //     //删除已选医生
      //     await that.doctorDelFun();

      //
      //     that.$emit("refreshConsultantTeam", consTeam)
      //   }).catch(() => {
      //     console.log("取消选择")
      //   });
      // }
    },
    doctorDelFun() {
      this.consultantDoctorData.forEach(async (item, index) => {
        await this.doctorDel(item.id)
        if (this.consultantDoctorData.length == index + 1) {
          this.$emit('refreshDoctorlist')
        }
      })
    },
    getTeamHospitalDepData(data) {
      const _obj = {
        // 申请会诊方团队/医院/科室
        TeamName: data.team ? data.team.teamName : null,
        TeamId: data.team ? data.team.id : null,
        HospitalName: data.hospital ? data.hospital.name : null,
        HospitalId: data.hospital ? data.hospital.id : null,
        DepName: data.department ? data.department.departmentName : null,
        DepartmentId: data.department ? data.department.id : null
      }
      return _obj
    },
    // 选择医生确认
    selectedDoctor(doctorInfo) {
      const that = this
      let teamTxt = ''
      let teamIsSelect = false // 判断是否已选团队医院科室
      Object.keys(that.consultantTeam).forEach(key => {
        if (that.consultantTeam[key] != '' && that.consultantTeam[key] != null) {
          teamIsSelect = true
        }
      })
      if (teamIsSelect) {
        teamTxt = '删除已选会诊方，并'
      }

      that.$confirm('确认' + teamTxt + '选择 ' + doctorInfo.userName + ' 医生会诊？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (teamIsSelect) {
          // 清除已选团队医院科室
          const _obj = {
            // 申请会诊方团队/医院/科室
            TeamName: null,
            TeamId: null,
            HospitalName: null,
            HospitalId: null,
            DepName: null,
            DepartmentId: null
          }
          that.$emit('refreshConsultantTeam', _obj)
        }
        that.postSelectedDoctor([doctorInfo])
      }).catch(() => {
        console.log('取消选择')
      })
    },
    // 选择会诊医生，多选
    selectedDoctorMDT() {
      // if (!this.zzId) {
      //   this.$message.warning('请选择主责~')
      // } else {
      const that = this
      const doctorArr = this.doctorData.filter(item => item.selected == 'selected_active')
      const titleDoctor = doctorArr.map(item => { return item.userName })
      if (titleDoctor.length == 0) {
        this.$message.warning('请选择会诊医生！')
        return
      }
      let teamTxt = ''
      let teamIsSelect = false // 判断是否已选团队医院科室
      Object.keys(that.consultantTeam).forEach(key => {
        if (that.consultantTeam[key] != '' && that.consultantTeam[key] != null) {
          teamIsSelect = true
        }
      })
      if (teamIsSelect) {
        teamTxt = '删除已选会诊方，并'
      }

      this.$confirm('确认' + teamTxt + '选择 ' + titleDoctor.join('、') + ' 医生会诊？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (teamIsSelect) {
          // 清除已选团队医院科室
          const _obj = {
            // 申请会诊方团队/医院/科室
            TeamName: null,
            TeamId: null,
            HospitalName: null,
            HospitalId: null,
            DepName: null,
            DepartmentId: null
          }
          that.$emit('refreshConsultantTeam', _obj)
        }
        this.postSelectedDoctor(doctorArr)
      }).catch(() => {
        console.log('取消选择')
      })
      // }
    },
    // 主责
    zzIdSelected(id) {
      this.zzId = id
    },
    // 选择会诊医生提交
    postSelectedDoctor(info) {
      const that = this
      if (info) {
        const _len = info.length
        let paramsArr = []
        for (var i = 0; i < _len; i++) {
          paramsArr[i] = {}
          paramsArr[i].applyId = that.consultationId
          paramsArr[i].hospital = info[i].hospitalName
          paramsArr[i].department = info[i].deptName
          paramsArr[i].position = info[i].position
          paramsArr[i].expertId = info[i].id
          paramsArr[i].status = '0'
          paramsArr[i].applyTheme = that.applyTheme
          // applyTheme:3，mdt会诊申请，多选
          if (_len == 1 && that.applyTheme != '3') {
            paramsArr[i].responsible = '1' // 主责
          } else {
            const _hasZz = that.consultantDoctorData.findIndex(item => item.responsible == 1)
            if (_hasZz >= 0) {
              paramsArr[i].responsible = '0'
            } else {
              paramsArr[i].responsible = i == 0 ? '1' : '0'
              // paramsArr[i].responsible = info[i].id == this.zzId ? '1' : '0';
            }
          }
        }
        if (that.applyTheme != '3' && that.consultantDoctorData.length > 0) {
          that.doctorDel(that.consultantDoctorData[0].id, paramsArr)
        } else {
          postRemoteExpertDiagnosisAddRemoteExperts(paramsArr).then((res) => {
            if (res && res.code == 10000) {
              that.consDlgShow = false
              that.$emit('refreshDoctorlist')
            }
          })
        }
      }
    },
    // 删除医生
    async doctorDel(id, paramsArr) {
      const that = this
      if (id) {
        await deleteRemoteExpertDiagnosis({ id: id }).then(res => {
          // if (res && res.code == 10000) {
          // }
        })
        if (paramsArr) {
          postRemoteExpertDiagnosisAddRemoteExperts(paramsArr).then((res) => {
            if (res && res.code == 10000) {
              that.consDlgShow = false
              that.$emit('refreshDoctorlist')
            }
          })
        }
      }
    }
  },
  watch: {
    teamOrHospitalName() {
      this.teamHospitalChange()
    },
    'consultantDoctorForm.Doctor': {
      handler: function () {
        this.HospDepDocChange()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.consultant_dailog {
  // text-align: center;
  .header-title {
    display: flex;
    align-items: center;
    .goback {
      cursor: pointer;
      font-size: 22px;
    }
  }
  .loading_box {
    min-height: 100px;
  }
  .cons_container {
    padding:0 20px;
    min-height: 76vh;
    height: calc(100% - 48px);
    overflow-y: auto;
    .cons_doctor_form,
    .cons_teamHospital_form {
      border-bottom: solid 1px #f3f3f3;
      padding-bottom: 10px;
    }
    .form_item_doctor {
      border-right: solid 1px #eee;
      margin-right: 16px;
      padding-right: 20px;
    }
    .cons_doctor_grid {
      display: flex;
      flex-wrap: wrap;
    }
  }
  .cons_footer {
    padding-left: 20px;
    overflow: hidden;
    .page_wrap {
      padding-right: 200px;
      // text-align: center;
    }
    .nav_save {
      float: right;
    }
  }
}
</style>
